/*
 * MIT License
 *
 * Copyright (c) 2024 sky2080
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.sky.disruptor;

import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventTranslatorTwoArg;
import com.lmax.disruptor.ExceptionHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
public class DisruptorQueueHandler<T> implements DisruptorQueue<T> {

  public static final String QUEUE_HANDLER_IS_CLOSE = "DisruptorQueueHandler is close";
  private final Map<String, DisruptorEventListener<T>> disruptorEventListeners;
  private final EventTranslatorTwoArg<DisruptorEvent, String, T> eventTranslator;
  private RingBuffer<DisruptorEvent> ringBuffer;
  private final Disruptor<DisruptorEvent> disruptor;

  private DisruptorQueueHandler(Builder<T> builder) {

    this.eventTranslator = new DisruptorEventTranslator();
    this.disruptorEventListeners = builder.listeners;

    //创建多个消费者组
    WorkHandler<DisruptorEvent>[] workHandlers = new WorkHandler[builder.threads];
    for (int i = 0; i < workHandlers.length; i++) {
      workHandlers[i] = new DisruptorWorkHandler();
    }

    disruptor = new Disruptor<>(new DisruptorEventFactory(), builder.bufferSize, new ThreadFactoryBuilder().
      setNameFormat("DisruptorQueueHandler" + builder.namePrefix + "-pool-%d").build(), builder.producerType, builder.waitStrategy);
    disruptor.handleEventsWithWorkerPool(workHandlers);
    disruptor.setDefaultExceptionHandler(new DisruptorExceptionHandler());
  }

  @Override
  public void start() {
    this.ringBuffer = disruptor.start();
  }

  private static <E> void process(DisruptorEventListener<E> listener, Throwable e, E event) {
    listener.onException(e, -1, event);
  }

  @Override
  public void add(String topic, T event) {
    RingBuffer<DisruptorEvent> holderRing = ringBuffer;
    if (holderRing == null) {
      process(disruptorEventListeners.get(topic), new IllegalStateException(QUEUE_HANDLER_IS_CLOSE), event);
      return;
    }
    try {
      ringBuffer.publishEvent(this.eventTranslator, topic, event);
    } catch (NullPointerException e) {
      process(disruptorEventListeners.get(topic), new IllegalStateException(QUEUE_HANDLER_IS_CLOSE), event);
    }
  }

  @Override
  public void shutDown() {
    RingBuffer<DisruptorEvent> holder = ringBuffer;
    ringBuffer = null;
    if (holder == null) {
      return;
    }
    if (disruptor != null) {
      disruptor.shutdown();
    }
  }

  @Override
  public boolean isShutDown() {
    return ringBuffer == null;
  }


  public static class Builder<T> {

    private ProducerType producerType = ProducerType.MULTI;

    private int bufferSize = 1024 * 16;

    private int threads = 1;

    private String namePrefix = "disruptor";

    private WaitStrategy waitStrategy = new BlockingWaitStrategy();

    private Map<String, DisruptorEventListener<T>> listeners;


    public Builder<T> setProducerType(ProducerType producerType) {
      Preconditions.checkNotNull(producerType);
      this.producerType = producerType;
      return this;
    }

    public Builder<T> setBufferSize(int bufferSize) {
      Preconditions.checkArgument(Integer.bitCount(bufferSize) == 1);
      this.bufferSize = bufferSize;
      return this;
    }

    public Builder<T> setThreads(int threads) {
      Preconditions.checkArgument(threads > 0);
      this.threads = threads;
      return this;
    }

    public Builder<T> setNamePrefix(String namePrefix) {
      Preconditions.checkNotNull(namePrefix);
      this.namePrefix = namePrefix;
      return this;
    }

    public Builder<T> setWaitStrategy(WaitStrategy waitStrategy) {
      Preconditions.checkNotNull(waitStrategy);
      this.waitStrategy = waitStrategy;
      return this;
    }

    public void setListeners(Map<String, DisruptorEventListener<T>> listeners) {
      if (CollectionUtils.isEmpty(listeners)) {
        throw new NullPointerException();
      }
      this.listeners = listeners;
    }
    public DisruptorQueueHandler<T> build() {
      return new DisruptorQueueHandler<>(this);
    }
  }

  public class DisruptorEvent {

    private String topic;
    private T event;

    public String getTopic() {
      return topic;
    }

    public void setTopic(String topic) {
      this.topic = topic;
    }

    public void setValue(T event) {
      this.event = event;
    }

    public void clear() {
      this.setTopic(null);
      this.setValue(null);
    }
  }

  /**
   *
   */
  private class DisruptorEventTranslator implements EventTranslatorTwoArg<DisruptorEvent, String, T> {
    @Override
    public void translateTo(DisruptorEvent disruptorEvent, long l, String topic, T e) {
      disruptorEvent.setTopic(topic);
      disruptorEvent.setValue(e);
    }
  }


  private class DisruptorEventFactory implements EventFactory<DisruptorEvent> {
    @Override
    public DisruptorEvent newInstance() {
      return new DisruptorEvent();
    }
  }

  /**
   * 实现workHandler 使用自定义disruptorEventListeners 处理数据
   */
  private class DisruptorWorkHandler implements WorkHandler<DisruptorEvent> {
    @Override
    public void onEvent(DisruptorEvent disruptorEvent) {
      disruptorEventListeners.get(disruptorEvent.getTopic()).onEvent(disruptorEvent.event);
      disruptorEvent.clear();
    }
  }

  /**
   * 实现ExceptionHandler 处理onEvent 报错数据
   */
  private class DisruptorExceptionHandler implements ExceptionHandler<DisruptorEvent> {
    @Override
    public void handleEventException(Throwable throwable, long l, DisruptorEvent event) {
      try {
        disruptorEventListeners.get(event.getTopic()).onException(throwable, l, event.event);
      } catch (Exception e) {
        log.error("handleEventException", e);
      } finally {
        event.setValue(null);
      }
    }

    @Override
    public void handleOnStartException(Throwable throwable) {
      throw new UnsupportedOperationException(throwable);
    }

    @Override
    public void handleOnShutdownException(Throwable throwable) {
      throw new UnsupportedOperationException(throwable);
    }
  }

}
